package com.wuhao.shootclient.ui.widget;

import android.content.Context;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.wuhao.shootclient.util.DisplayUtil;


/**
 * 可拖动视图 转换类
 */
public class DragViewWrapper {
    protected Context context;
    protected ViewGroup mParentView;
    protected View childView;

    protected FrameLayout.LayoutParams childViewFLP;
    private float parentL;
    private float parentT;
    private float parentWidth;
    private float parentHeight;

    private float childWidth;
    private float childWidthHalf;
    private float childHeight;
    private float childHeightHalf;

    private boolean draggable;//是否可拖动

    //滑动范围
    private int marginTop;
    private int marginBottom;

    public DragViewWrapper() {
        childViewFLP = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        childViewFLP.gravity = (Gravity.TOP | Gravity.END);
        draggable = true;
    }

    /**
     * 传入一个新的 子view（新new的view，不需要从父view中移除）使其可拖拽
     *
     * @param childView 传入子view
     */
    public DragViewWrapper addNewChildView(View childView) {
        context = childView.getContext();
        this.childView = childView;
        marginTop = DisplayUtil.dip2px(context, 70);

        if (context instanceof AppCompatActivity) {
            childView.setLayoutParams(childViewFLP);

            childView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    childView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    addTouchFloat();
                }
            });

            mParentView = ((AppCompatActivity) context).getWindow().getDecorView().findViewById(android.R.id.content);
            mParentView.addView(childView);
            if (onChildViewListener != null) {
                onChildViewListener.afterAddChild(childView);
            }
        }


        return this;
    }

    /**
     * 传入一个 已经存在布局中的view（需要将其从父view中移除） 使其可拖拽
     *
     * @param childView 传入子view
     */
    public DragViewWrapper addOldChildView(View childView) {
        context = childView.getContext();
        this.childView = childView;
        childView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                childView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                if (context instanceof AppCompatActivity) {
                    ViewGroup parent = (ViewGroup) childView.getParent();
                    parent.removeView(childView);

                    mParentView = ((AppCompatActivity) context).getWindow().getDecorView().findViewById(android.R.id.content);

                    childView.setLayoutParams(childViewFLP);

                    addTouchFloat();
                    mParentView.addView(childView);
                    if (onChildViewListener != null) {
                        onChildViewListener.afterAddChild(childView);
                    }
                }
            }
        });
        return this;

    }

    private float firstX;
    private float firstY;
    boolean isMove = false;

    private DragViewWrapper addTouchFloat() {
        if (childViewFLP != null) {

            int[] pLoc = new int[2];
            mParentView.getLocationOnScreen(pLoc);
            parentL = pLoc[0];
            parentT = pLoc[1];
            parentWidth = mParentView.getWidth();
            parentHeight = mParentView.getHeight();

            childWidth = childView.getWidth();
            childWidthHalf = childWidth / 2;
            childHeight = childView.getHeight();
            childHeightHalf = childHeight / 2;

            childView.setOnTouchListener((v, event) -> {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        firstX = event.getRawX();
                        firstY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:

                        if (isMove || (Math.abs(firstX - event.getRawX()) > 10) || (Math.abs(firstY - event.getRawY()) > 10)) {
                            isMove = true;
                            if (draggable) {
                                float touchX = event.getRawX() - parentL - childWidthHalf;
                                float touchY = event.getRawY() - parentT - childHeightHalf;

                                childViewFLP.gravity = Gravity.TOP | Gravity.START;
                                if (touchY <= marginTop) {
                                    touchY = marginTop;
                                } else if (touchY >= (parentHeight - childHeight - marginBottom)) {
                                    touchY = parentHeight - childHeight - marginBottom;
                                }
                                childViewFLP.topMargin = (int) touchY;

                                if (touchX <= 0) {
                                    touchX = 0;
                                } else if (touchX >= (parentWidth - childWidth)) {
                                    touchX = parentWidth - childWidth;
                                }
                                childViewFLP.leftMargin = (int) touchX;

                                childView.setLayoutParams(childViewFLP);
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (isMove) {
                            isMove = false;
                            if (childViewFLP.leftMargin < parentWidth / 2) {
                                childViewFLP.leftMargin = 0;
                            } else {
                                childViewFLP.leftMargin = (int) (parentWidth - childWidth);
                            }
                            childView.setLayoutParams(childViewFLP);

                        } else {
                            childView.performClick();
                        }
                        break;
                }

                return true;
            });
        }

        return this;
    }


    private OnChildViewListener onChildViewListener;

    public interface OnChildViewListener {
        void afterAddChild(View childView);
    }

    /**
     * 设置 添加子view监听
     *
     * @param onChildViewListener
     * @return
     */
    public DragViewWrapper setOnChildViewListener(OnChildViewListener onChildViewListener) {
        this.onChildViewListener = onChildViewListener;
        return this;
    }

    /**
     * 设置 初始 位置（相对于屏幕 右上角）
     *
     * @param topMargin
     * @param rightMargin
     * @return
     */
    public DragViewWrapper setLocation(int topMargin, int rightMargin) {
        childViewFLP.topMargin = DisplayUtil.dip2px(context, topMargin);
        childViewFLP.rightMargin = DisplayUtil.dip2px(context, rightMargin);
        childView.setLayoutParams(childViewFLP);
        return this;
    }


    /**
     * 设置上下滑动边界
     *
     * @param top
     * @param bottom
     * @return
     */
    public DragViewWrapper setMargin(int top, int bottom) {
        marginTop = top;
        marginBottom = bottom;
        return this;
    }

    /**
     * 设置是否可拖动
     *
     * @param draggable
     * @return
     */
    public DragViewWrapper setDraggable(boolean draggable) {
        this.draggable = draggable;
        return this;
    }
}
